//
//  SearchViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/9/9.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "SearchViewController.h"

#import "BuyCarCell.h"
#import "DianPuViewController.h"
@interface SearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>{
    NSMutableArray *array;
    NSMutableArray *datas;//历史记录
    UIView *NoView;
}

@property (nonatomic,copy)NSString *searchStr;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UITableView *tableViewHis;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setBGColor];
    [self showNav:@"搜索"];
    array = [NSMutableArray array];
    datas = [NSMutableArray array];
    [self loadUI];
    datas = [user objectForKey:@"myArray"];
    
}

- (void)loadUI{
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, 30)];
    searchBar.placeholder = @"输入您想搜索的内容";
//    [searchBar setShowsCancelButton:YES animated:YES];
    searchBar.delegate = self;
    [self.view addSubview:searchBar];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 94, ScreenWidth, ScreenHeight-94) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.hidden = YES;
    [self.view addSubview:_tableView];
    
    _tableViewHis = [[UITableView alloc] initWithFrame:CGRectMake(0, 94, ScreenWidth, ScreenHeight-94) style:UITableViewStylePlain];
    _tableViewHis.delegate = self;
    _tableViewHis.dataSource = self;
    _tableViewHis.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableViewHis];
    
    NoView = [[UIView alloc] initWithFrame:CGRectMake(0, 94, ScreenWidth, ScreenHeight-94)];
    NoView.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    NoView.hidden = YES;
    [self.view addSubview:NoView];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 20)];
    lab.text = @"抱歉，没找到您想搜索的内容-_-";
    [NoView addSubview:lab];
    
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    NSLog(@"点击搜索框");
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    
    return YES;
}
//点击搜索按钮
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    _searchStr = searchBar.text;
    //读取数组NSArray类型的数据
    NSArray *myArray = [[NSArray alloc] initWithArray:[user arrayForKey:@"myArray"]];
    
    // NSArray --> NSMutableArray
    NSMutableArray *searTXT = [NSMutableArray array];
    searTXT = [myArray mutableCopy];
    
    BOOL isEqualTo1,isEqualTo2;
    isEqualTo1 = NO,isEqualTo2 = NO;
    
    if (searTXT.count > 0) {
        isEqualTo2 = YES;
        //判断搜索内容是否存在，存在的话放到数组最后一位，不存在的话添加。
        for (NSString * str in myArray) {
            if ([_searchStr isEqualToString:str]) {
                //获取指定对象的索引
                NSUInteger index = [myArray indexOfObject:_searchStr];
                [searTXT removeObjectAtIndex:index];
                [searTXT addObject:_searchStr];
                isEqualTo1 = YES;
                break;
            }
        }
    }
    
    if (!isEqualTo1 || !isEqualTo2) {
        [searTXT addObject:_searchStr];
    }
    
    if(searTXT.count > 15)
    {
        [searTXT removeObjectAtIndex:0];
    }
    //购车历史
    [user setObject:searTXT forKey:@"myArray"];
    [self loadData:_searchStr];
    [searchBar resignFirstResponder];
}
//点击取消按钮
-(void)searchBarCancelButtonClicked:(UISearchBar*)searchBar
{
    NSLog(@"searchBarCancelButtonClicked");
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _tableView) {
        return array.count;
    }else{
        return datas.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        static NSString *cellId = @"Cell2";
        BuyCarCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BuyCarCell" owner:nil options:nil] lastObject];
        }
        //取消选中效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSDictionary *dic = array[indexPath.row];
        cell.labPrice1.text = [NSString stringWithFormat:@"%@万",[dic objectForKey:@"sellingprice"]];
        
        cell.labName.text = [dic objectForKey:@"name"];
        cell.labStyle.text = [dic objectForKey:@"brand"];
        cell.labPrice2.text = [NSString stringWithFormat:@"%@万",[dic objectForKey:@"guideprice"]];
        //
        NSString *km = [NSString stringWithFormat:@" %.2fkm",[[dic objectForKey:@"km"] floatValue]];
        
        NSString *countcomment = [NSString stringWithFormat:@" %li",[[dic objectForKey:@"countcomment"] integerValue]];
        NSString *thenumberof = [NSString stringWithFormat:@" %li",[[dic objectForKey:@"thenumberof"] integerValue]];
        if ([thenumberof integerValue] > 10000) {
            [cell.btnCenter setTitle:[NSString stringWithFormat:@"%.1f万",[thenumberof floatValue]/10000.0] forState:UIControlStateNormal];
        }else{
            [cell.btnCenter setTitle:thenumberof forState:UIControlStateNormal];
        }
        //
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[dic objectForKey:@"carthemephoto"]];
        //星
        NSString *xin = [dic objectForKey:@"star"];
        CGFloat count = [xin floatValue];
        
        StarView *staView = [[StarView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
        staView.showStar = count * 20;
        [cell.sview addSubview:staView];
        
        [cell.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"timg-(1)"]];
        
        [cell.btnLeft setTitle:km forState:UIControlStateNormal];
        [cell.btnRight setTitle:countcomment forState:UIControlStateNormal];
        [cell.btnCenter setImage:[UIImage imageNamed:@"浏览"] forState:UIControlStateNormal];
        
        return cell;
    }else{
        static NSString *cellId = @"Cell0";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = datas[indexPath.row];
        
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        return 163.0;
    }
    return 44.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    view.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(16, 10, 100, 20)];
    lab.text = @"历史搜索";
    [view addSubview:lab];
    
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == _tableViewHis) {
        return 40.0;
    }
    return 0.0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableViewHis) {
        NSString *str = datas[indexPath.row];
        [self loadData:str];
    }else{
        NSDictionary *dic = array[indexPath.row];
        NSString *carid = [dic objectForKey:@"id"];
        NSString *name = [dic objectForKey:@"name"];
        NSString *place = [dic objectForKey:@"suite"];
        NSString *llcount = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"thenumberof"] integerValue]];
        NSString *start = [NSString stringWithFormat:@"%.2f",[[dic objectForKey:@"star"] floatValue]];
        NSString *km = [NSString stringWithFormat:@"%.2fkm",[[dic objectForKey:@"km"] floatValue]];
        //图片数组
        NSString *figurepic = [dic objectForKey:@"figurepic"];
        NSArray *arr = [figurepic componentsSeparatedByString:@"|"];
        NSMutableArray *images = [NSMutableArray array];
        for (NSString *imgFoot in arr) {
            NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],imgFoot];
            [images addObject:imgUrl];
        }
        
        DianPuViewController *dianpu = [[DianPuViewController alloc] init];
        dianpu.CarId = carid;
        dianpu.name = name;
        dianpu.place = place;
        dianpu.count = llcount;
        dianpu.start = start;
        dianpu.arrays = images;
        dianpu.km = km;
        dianpu.lat = _lat;
        dianpu.lng = _lng;
        [self.navigationController pushViewController:dianpu animated:YES];
    }
    
}
//购车店铺列表
- (void)loadData:(NSString *)str{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setValue:_lng forKey:@"longitude"];
    [parmas setValue:_lat forKey:@"latitude"];
    [parmas setValue:@"1" forKey:@"p"];
    [parmas setValue:str forKey:@"name"];
    [parmas setValue:_area forKey:@"addres"];
    NSLog(@"parmas:%@",parmas);
    NSString *url = [NSString stringWithFormat:@"%@/App/CarBuying/index",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"购车res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            array = [responseObject objectForKey:@"result"];
            _tableView.hidden = NO;
            _tableViewHis.hidden = YES;
            NoView.hidden = YES;
            [_tableView reloadData];
        }else{
            _tableView.hidden = YES;
            _tableViewHis.hidden = YES;
            NoView.hidden = NO;
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
